package entity

import (
	"errors"
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/workflow"
	"shqsoft.cn/pas3ui/workflow/entity"
)

//IndiAccoWorkflowNew 零售新客户认定审批
type IndiAccoWorkflowNew struct {
	ID       int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	IDNO     string    `gorm:"column:IDNO"`
	CUNM     string    `gorm:"column:CUNM"`
	CUID     int       `gorm:"column:CUID"`
	EMNO1    string    `gorm:"column:EMNO1"`
	EMID1    int       `gorm:"column:EMID1"`
	EMNM1    string    `gorm:"-" json:"emnm1"`
	DSVL1    float64   `gorm:"column:DSVL1"`
	EMNO2    string    `gorm:"column:EMNO2"`
	EMNM2    string    `gorm:"-" json:"emnm2"`
	EMID2    int       `gorm:"column:EMID2"`
	DSVL2    float64   `gorm:"column:DSVL2"`
	EMNO3    string    `gorm:"column:EMNO3"`
	EMNM3    string    `gorm:"-" json:"emnm3"`
	EMID3    int       `gorm:"column:EMID3"`
	DSVL3    float64   `gorm:"column:DSVL3"`
	EMNO4    string    `gorm:"column:EMNO4"`
	EMNM4    string    `gorm:"-" json:"emnm4"`
	EMID4    int       `gorm:"column:EMID4"`
	DSVL4    float64   `gorm:"column:DSVL4"`
	UID      int       `gorm:"column:UID"`
	FRID     int       `gorm:"column:FRID"`
	WFID     int       `gorm:"column:WFID"`
	OPDT     time.Time `gorm:"column:OPDT"`
	SQR      string    `gorm:"column:SQR"`
	SQDT     time.Time `gorm:"column:SQDT"`
	STEP     int       `gorm:"-" json:"step"`
	Progress float64   `gorm:"-" json:"progress"`
	StepName string    `gorm:"-" json:"stepName"`
	Status   string    `gorm:"-" json:"status"`
}

//TableName 对公客户认定审批
func (IndiAccoWorkflowNew) TableName() string {
	return "T_INDI_CLIE_DIVI"
}

//BeforeSave 保存前的触发器
func (i *IndiAccoWorkflowNew) BeforeSave(tx *gorm.DB) (err error) {
	if i.CUID > 0 {
		sqlEx := `select "IDNO","CUNM" from "DICT_INDI_CLIE" where "ID"=?`
		row := base.CHDB.Raw(sqlEx, i.CUID).Row()
		row.Scan(&i.IDNO, &i.CUNM)
	} else {
		sqlEx := `select "ID" from "DICT_INDI_CLIE" where "IDNO"=? and "CUNM"=?`
		row := base.CHDB.Raw(sqlEx, i.IDNO, &i.CUNM).Row()
		row.Scan(&i.CUID)
		if i.CUID == 0 {
			return fmt.Errorf("客户:%s,证件号码:%s不匹配或在系统中不存在！", i.CUNM, i.IDNO)
		}
	}
	var count int
	sqlEx := `SELECT COUNT() NUM FROM JOIN_INDI_ACCO_ISDIVI WHERE CUID=? AND ISRD=1`
	row := base.CHDB.Raw(sqlEx, i.CUID).Row()
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("客户%s,证件号码%s已认定，请走变更流程！", i.CUNM, i.IDNO)
	}
	sqlEx = `select MIN(OPDT) OPDT from T_INDI_ACCO where CUID=?`
	row = base.CHDB.Raw(sqlEx, i.CUID).Row()
	row.Scan(&i.OPDT)
	sum := i.DSVL1 + i.DSVL2 + i.DSVL3 + i.DSVL4
	if sum != 100 {
		return errors.New("占比之和必须为100！")
	}
	ec := base.GetEmployeeCache()
	ec.GetIdByNo(i.EMNO1)
	i.EMID1, err = ec.GetIdByNo(i.EMNO1)
	if err != nil || i.EMID1 == 0 {
		err = fmt.Errorf("员工工号1:%s在系统中没有找到！", i.EMNO1)
		return
	}
	i.EMNM1, _ = ec.GetNameByID(i.EMID1)
	if i.UID == 0 {
		i.UID = i.EMID1
	}
	if i.DSVL2 > 0 {
		ec.GetIdByNo(i.EMNO2)
		i.EMID2, err = ec.GetIdByNo(i.EMNO2)
		if err != nil || i.EMID2 == 0 {
			err = fmt.Errorf("员工工号2:%s在系统中没有找到！", i.EMNO2)
			return
		}
		i.EMNM2, _ = ec.GetNameByID(i.EMID2)
	}
	if i.DSVL3 > 0 {
		ec.GetIdByNo(i.EMNO3)
		i.EMID3, err = ec.GetIdByNo(i.EMNO3)
		if err != nil || i.EMID3 == 0 {
			err = fmt.Errorf("员工工号3:%s在系统中没有找到！", i.EMNO3)
			return
		}
		i.EMNM3, _ = ec.GetNameByID(i.EMID3)
	}
	if i.DSVL4 > 0 {
		ec.GetIdByNo(i.EMNO4)
		i.EMID4, err = ec.GetIdByNo(i.EMNO4)
		if err != nil || i.EMID4 == 0 {
			err = fmt.Errorf("员工工号4:%s在系统中没有找到！", i.EMNO4)
			return
		}
		i.EMNM4, _ = ec.GetNameByID(i.EMID4)
	}
	if i.DSVL1 <= 50 && i.DSVL2 <= 50 && i.DSVL3 <= 50 && i.DSVL4 <= 50 {
		err = errors.New("必须有一个员工的占比大于50")
		return
	}
	if i.ID == 0 {
		var count int
		sqlStr := `select count(a."ID") from "T_INDI_CLIE_DIVI" a inner join "T_FLOW_RUN" b on a."FRID"=b."ID" where b."STATE"='0' and a."CUID"=?`
		row := tx.Raw(sqlStr, i.CUID).Row()
		row.Scan(&count)
		if count > 0 {
			return fmt.Errorf("客户:%s_%s已经在申请中，不能重复申请！", i.CUNM, i.IDNO)
		}
	}
	if i.ID > 0 {
		row := base.MYDB.Model(IndiAccoWorkflowNew{}).Where(`"ID"=?`, i.ID).Select(`"FRID"`).Row()
		row.Scan(&i.FRID)
	}
	if i.FRID == 0 {
		ei, _ := workflow.GetEntityInfo("IndiAccoWorkflowNew")
		i.WFID, err = ei.WfidFunc(i)
		if err != nil {
			return err
		}
		if i.WFID == 0 {
			return errors.New("获取新零售账户申请WFID失败")
		}
		runid, err := workflow.Create(i.WFID, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}
	i.SQDT = time.Now()
	return
}

// AfterFind 查询后触发器
func (i *IndiAccoWorkflowNew) AfterFind(tx *gorm.DB) (err error) {
	ec := base.GetEmployeeCache()
	i.EMNM1, err = ec.GetNameByID(i.EMID1)
	if err != nil {
		return err
	}
	if i.DSVL2 > 0 {
		i.EMNM2, err = ec.GetNameByID(i.EMID2)
		if err != nil {
			return err
		}
	}
	if i.DSVL3 > 0 {
		i.EMNM3, err = ec.GetNameByID(i.EMID3)
		if err != nil {
			return err
		}
	}
	if i.DSVL4 > 0 {
		i.EMNM4, err = ec.GetNameByID(i.EMID4)
		if err != nil {
			return err
		}
	}
	i.IDNO = base.IndoTM(i.IDNO)
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func (i *IndiAccoWorkflowNew) AfterDelete(tx *gorm.DB) (err error) {
	if i.FRID > 0 {
		return workflow.DeleteWithTx(i.FRID, tx)
	}
	return nil
}

func IndiAccoWorkflowNewEF() base.EntityFunc {
	return func() interface{} {
		entity := IndiAccoWorkflowNew{}
		return &entity
	}
}
func IndiAccoWorkflowNewESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []IndiAccoWorkflowNew
		return &entities
	}
}

func getIndiAccoWorkflowNewWfidSh(params interface{}) (wfid int, err error) {
	return 3, nil
}
func getIndiAccoWorkflowNewWfidSz(params interface{}) (wfid int, err error) {
	return
}

func init() {
	workflow.SetWfidFunc("getIndiAccoWorkflowNewWfidSh", getIndiAccoWorkflowNewWfidSh)
	workflow.SetWfidFunc("getIndiAccoWorkflowNewWfidSz", getIndiAccoWorkflowNewWfidSz)
	ei, err := workflow.GetEntityInfo("IndiAccoWorkflowNew")
	if err != nil {
		panic(err)
	}
	dao := base.NewDefaultDao(IndiAccoWorkflowNewEF(), IndiAccoWorkflowNewESF(), nil, "my")
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", ei.WfidsToString())
	filter.SetAdditional("manager", ei.MgMapToString())
	dao.Fileter = &filter
	dao.Fileter.SetDB("my")
	base.DaoPoolObj.Put("IndiAccoWorkflowNew", dao)
}
